from scipy.optimize import minimize
import numpy as np

# 目标函数
def objective(x):
    return -(4.8*x[0] + 4.8*x[2] + 5.6*x[1] + 5.6*x[3] - c(x[4]))

def c(x):
    if 0 <= x <= 500:
        return 10 * x
    elif 500 < x <= 1000:
        return 1000 + 8 * x
    elif 1000 < x <= 1500:
        return 3000 + 6 * x
    else:
        return float('inf')  # 如果 x 超过 1500，返回无穷大

# 不等式约束
def constraint1(x):
    return 500 + x[4] - x[0] - x[1] #>=0

def constraint2(x):
    return 1000 - x[2] - x[3]

def constraint3(x):
    return 1500 - x[4]

def constraint4(x):
    if x[0] + x[2] == 0:
        return -0.5  # 如果分母为零，返回一个负值以表示约束不满足
    return (x[0] / (x[0] + x[2])) - 0.5

def constraint5(x):
    if x[1] + x[3] == 0:
        return -0.6  # 如果分母为零，返回一个负值以表示约束不满足
    return (x[1] / (x[1] + x[3])) - 0.6

# 初始猜测
x0 = np.zeros(5)

# 变量的边界
bounds = [(0, None)] * 5

# 约束
constraints = [
    {'type': 'ineq', 'fun': constraint1},
    {'type': 'ineq', 'fun': constraint2},
    {'type': 'ineq', 'fun': constraint3},
    {'type': 'ineq', 'fun': constraint4},
    {'type': 'ineq', 'fun': constraint5},
]

# 求解非线性规划问题
result = minimize(objective, x0, method='SLSQP', bounds=bounds, constraints=constraints)

# 输出结果
print('最优解：', result.x)
print('最优目标函数值：', -result.fun)  # 由于目标函数系数取负，所以结果也要取负